package talib

import "math"

// 计算平均值
func MA(x []float64, n int) (v []float64) {
	l := len(x)
	v = make([]float64, l)

	i := 0
	sum := 0.0
	idx := 0
	offset := 0
	for ; i < l; i++ {
		if math.IsNaN(x[i]) {
			v[i] = math.NaN()
			offset++
			continue
		}
		sum += x[i]
		v[i] = math.NaN()
		idx++
		if idx >= n {
			break
		}
	}
	idx += offset
	if idx < n {
		return v
	}
	v[idx-1] = sum / float64(n)
	for i := idx; i < l; i++ {
		if math.IsNaN(x[i]) || math.IsNaN(x[i-n]) {
			v[i] = math.NaN()
			continue
		}
		sum -= x[i-n]
		sum += x[i]
		v[i] = sum / float64(n)
	}
	return v
}

// 计算平均值,并将结果写入x
func Ma(x []*float64, n int) {
	l := len(x)
	v := make([]float64, l)

	i := 0
	sum := 0.0
	idx := 0
	offset := 0
	n1 := n
	for ; i < l; i++ {
		p := x[i]
		if p == nil {
			n1++
			idx++
			v[i] = math.NaN()
			continue
		}
		iv := *p
		if math.IsNaN(iv) {
			v[i] = math.NaN()
			offset++
			continue
		}
		sum += iv
		v[i] = math.NaN()
		idx++
		if idx >= n1 {
			break
		}
	}
	idx += offset
	if idx < n {
		return
	}
	v[idx-1] = sum / float64(n)
	for i := idx; i < l; i++ {
		p := x[i]
		if p == nil {
			v[i] = math.NaN()
			continue
		}
		q := x[i-n]
		if q == nil {
			v[i] = math.NaN()
			continue
		}
		fiv := *q
		iv := *p
		if math.IsNaN(iv) || math.IsNaN(fiv) {
			v[i] = math.NaN()
			continue
		}
		sum -= fiv
		sum += iv
		v[i] = sum / float64(n)
	}
	for i := 0; i < l; i++ {
		x[i] = &v[i]		
	}
}
